package beanstao.util.store.database;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import beanstao.util.Formula;

import com.google.common.collect.Maps;

/**
 * 数据集合的字段管理类，所指数据集合一般是指一张数据表或一个XML节点
 * @author beanstao@google.com 
 */
public class Fields implements Iterable<Entry<String, Field>>
{
	/**
	 * 构造函数
	 * @param tableName 数据表名
	 * @param fields 数据列集合
	 */
	public Fields(final String tableName, final Field... fields)
	{
		_name = tableName;
		for (Field field : fields)
			_Columns.put(field.getName().toLowerCase(), field);
	}

	/**
	 * 构造函数
	 * @param tableName 数据表名
	 * @param fields 数据列集合
	 */
	public Fields(final String tableName, final ArrayList<Field> fields)
	{
		_name = tableName;
		for (Field column : fields)
			_Columns.put(column.getName().toLowerCase(), column);
	}

	protected Map<String, Field> _Columns = Maps.newLinkedHashMap();

	protected final String _name;

	protected String _className;

	public String getClassName()
	{
		return _className;
	}

	public void setClassName(final String className)
	{
		_className = className;
	}

	/**
	 * @return 获得本字段管理类相应的表或XmlElement等的名字
	 */
	public String getName()
	{
		return _name;
	}

	public boolean containsKey(final Object key)
	{
		String keyString = String.valueOf(key).toLowerCase();
		return _Columns.containsKey(keyString);
	}

	public boolean containsValue(final Object value)
	{
		return _Columns.containsValue(value);
	}

	public Field get(final Object key)
	{
		String keyString = String.valueOf(key).toLowerCase();
		return _Columns.get(keyString);
	}

	public void put(final String key, final Field value)
	{
		_Columns.put(key, value);
	}

	public boolean isEmpty()
	{
		return _Columns.isEmpty();
	}

	public Set<String> keySet()
	{
		return _Columns.keySet();
	}

	public int size()
	{
		return _Columns.size();
	}

	public Collection<Field> values()
	{
		return _Columns.values();
	}

	public Iterator<Entry<String, Field>> iterator()
	{
		return _Columns.entrySet().iterator();
	}

	public Columns toSqlSelectFieldList()
	{
		Column selectField = new Column();
		selectField.append(new Formula("*"));
		Columns list = Columns.ME(selectField);
		return list;
	}

	@Override
	public String toString()
	{
		StringBuilder builder = new StringBuilder();
		for (Field field : _Columns.values())
			builder.append(field.getName()).append(',');
		return builder.toString();
	}

}
